import { useEffect, useState, useImperativeHandle, forwardRef, useRef } from 'react';
import { connect } from 'umi';
import * as echarts from 'echarts';
import { Modal, Select, Radio, Message } from 'antd';
import { configModal, config } from '@/assets';
import { HttpCode } from '#/utils/contacts.js';
import CustomPriceForecast from '../../components/CustomPriceForecast';
import { TRMessage } from '#/components';
import { TRDefault } from '@/components/index.js';
import styles from './index.less';
import { getCssVariableValue } from '@/utils/utils';
import configGre from '@/assets/config_gre.svg';
import { TjIcon } from '@/tjComponents/TjIcon';
import {
  fetchPriceForecastDatasourceList,
  fetchPriceForecastChartData,
  globalPriceDatasourceConfig,
  saveForecastVersion,
  getTjForecastPriceVersion,
  getTjForecastPriceByVersion,
} from '@/pages/Tianji/DayRollingTradeStrategy/services';
import { fetchTradePriceLimit } from '../../services';

const { Option } = Select;

function PriceForecastModal(
  {
    menuCode,
    tradeSeqId,
    stationId,
    stations,
    hourOrderList,
    tradeSeqList,
    echartsHourOrder,
    forecastDate,
    dispatch,
    provinceId,
    forecastPriceV,
  },
  ref,
) {
  useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const customPriceForecastRef = useRef();

  const [showModal, setShowModal] = useState(false),
    // 预测源列表
    [sourceList, setSourceList] = useState([]),
    // 日期版本列表
    [dateList, setDateList] = useState([]),
    // 选中的数据源id
    [selectedSourceId, setSelectedSourceId] = useState(
      stations?.[0]?.value ? [stations[0].value] : [],
    ),
    // 选中的数据源日期版本
    [selectedSourceDate, setSelectedSourceDate] = useState(null),
    // 交易限价
    [priceLimitData, setPriceLimitData] = useState([]),
    [checked, setChecked] = useState(false),
    [chartDomIns, setChartDomIns] = useState(null),
    [yAxisData, setYAxisData] = useState([]);

  /**
   * 关闭弹框时，清空选中数据
   */
  /*   useEffect(() => {
    if (!showModal) {
      setSelectedSourceId(stations?.[0]?.value || null);
      setSelectedSourceDate(null);
    }
  }, [showModal]); */

  /**
   * 当数据源id或者日期版本发生改变时，获取数据源图形数据
   */
  useEffect(() => {
    if (showModal && selectedSourceDate) {
      fetchPriceForecastChartDataAsync();
      dispatch({
        type: 'dayRollingTradeStragety/version2',
        payload: selectedSourceDate,
      });
    }
  }, [showModal, selectedSourceDate]);

  const initHandle = (value) => {
    setSelectedSourceId(value ? [value] : []);
    setShowModal(true);
    // 调用接口获取预测源列表
    fetchPriceForecastDatasourceListAsync();
  };

  // 获取现货价格预测数据源列表
  const fetchPriceForecastDatasourceListAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const params = {
      marketId: 'PHBSX',
      stationId,
      date: forecastDate,
    };
    const res = await getTjForecastPriceVersion(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let datasourceList = res?.data || [];
      // setSourceList(datasourceList);
      setDateList(datasourceList || []);
      setSelectedSourceDate(
        selectedSourceDate ? selectedSourceDate : res.data.length > 0 ? forecastPriceV : null,
      );

      /**
       * 初始化时，需要根据返回值设置选中值及版本列表，后续调用此接口，不再重新设置，保持用户的修改
       */
      /* if (selectedSourceId == stations?.[0]?.value) {
        setDateList(
          datasourceList?.filter((item) => item.id === res.data.selectedDatasourceId)?.[0]
            ?.versionDateList || [],
        );
        // setSelectedSourceId(res.data.selectedDatasourceId);
        setSelectedSourceDate(res.data.selectedVersionDate);
      } */
    } else {
      Message.error(res.message || '获取现货价格预测数据源列表失败');
    }
  };

  // 获取限价信息，获取数据成功后resolve
  const fetchTradePriceLimitAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await fetchTradePriceLimit({
      marketId: 'PHBSX', // 山西交易中心
      tradeType: '1', // 现货价格
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let priceLimitDataList = res?.data?.priceLimitDataList || [];
      setPriceLimitData(priceLimitDataList);
    } else {
      Message.error(res.message || '获取交易限价失败');
      throw new Error(res.message || '获取交易限价失败');
    }
  };

  // 获取电价预测数据源图表数据
  const fetchPriceForecastChartDataAsync = async () => {
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const params = {
      date: forecastDate,
      marketId: 'PHBSX',
      stationId,
      version: selectedSourceDate,
    };
    const res = await getTjForecastPriceByVersion(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let data = res?.data;
      setYAxisData(data?.yAxisData || []);
      initEchart(data?.xAxisData || [], data?.yAxisData?.map((item) => item.toFixed(3)) || []);
    } else {
      Message.error(res.message || '获取电价预测数据源echarts图数据失败');
    }
  };

  const changeSourceId = (value) => {
    setSelectedSourceId(value);
  };

  const initEchart = (xAxisData, yAxisData) => {
    chartDomIns && chartDomIns.dispose();

    var chartDom = document.getElementById('echart');
    var myChart = echarts.init(chartDom);
    var option = {
      color: ['#F5BE15'],
      grid: {
        left: '5%',
        right: '15',
        top: '30',
        bottom: '30',
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#161A1D',
        borderColor: 'transparent',
        textStyle: {
          color: '#A7A8A9',
        },
        formatter: (params) => {
          let str = `
           ${tradeSeqList
             .filter((item) => item.tradeSequenceId === tradeSeqId)[0]
             .forecastDate.replaceAll('-', '')} ${params[0].name}
           <br />
           ${params[0].marker} 现货价格预测 ${parseFloat(params[0].data).toFixed(2)}元/MWh
          `;
          return str;
        },
      },
      xAxis: {
        type: 'category',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        data: xAxisData,
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisPointer: {
          lineStyle: {
            color: getCssVariableValue('--chart-font-color'),
            type: 'solid',
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: 'value',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        // scale: true,
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
      series: [
        {
          data: yAxisData,
          type: 'line',
          smooth: true,
          symbol: 'none',
        },
      ],
    };
    myChart.setOption(option);
    setChartDomIns(myChart);
  };

  const updateTableData = (resData) => {
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    resData.forEach((item) => {
      const { timeOrder, forecastPrice } = item;
      const index = timeOrder - 1;
      if (index >= 0 && index < hourOrderListNew.length) {
        hourOrderListNew[index] = {
          ...hourOrderListNew[index],
          forecastPrice,
        };
      }
    });

    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  };
  /**
   * 设置现货价格预测数据源
   */
  const globalPriceDatasourceConfigAsync = async () => {
    const params = {
      forecastType: '2',
      stationId,
      stationIds: selectedSourceId,
      tradeSequenceId: tradeSeqId,
      version: selectedSourceDate,
      date: forecastDate,
    };
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await saveForecastVersion(params);
    dispatch({
      type: 'dayRollingTradeStragety/setForecastPriceV',
      payload: selectedSourceDate,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      setShowModal(false);
      updateTableData(res.data);
      TRMessage.success('设置成功');
      dispatch({
        type: 'dayRollingTradeStragety/setVersion2',
        payload: params.version,
      });
      dispatch({
        type: 'dayRollingTradeStragety/setVersion3',
        payload: '1',
      });
    } else {
      Message.error(res.message || '设置现货价格预测数据源失败');
    }
  };

  /**
   * 设置自定义数据源后，更新数据
   */
  const updateData = async (resData) => {
    updateTableData(resData);
    setShowModal(false);
    dispatch({
      type: 'dayRollingTradeStragety/setVersion3',
      payload: '2',
    });
    /* fetchPriceForecastDatasourceListAsync();
    fetchPriceForecastChartDataAsync(); */
  };

  /**
   * 自主调整
   */
  const customForecastHandle = async () => {
    // 获取限价信息，如果接口调用成功，则继续执行后续代码，否则，代码抛出错误，不再执行后续代码
    await fetchTradePriceLimitAsync();
    customPriceForecastRef.current.initHandle();
  };

  return (
    <Modal
      className={styles.priceForecastModal}
      centered={true}
      getContainer={false}
      title={
        <div className={styles.modalTitle}>
          <img src={configModal} />
          <span className={styles.text}>现货价格预测设置</span>
        </div>
      }
      visible={showModal}
      okText="提交"
      onCancel={() => {
        setShowModal(false);
      }}
      onOk={globalPriceDatasourceConfigAsync}
    >
      {dateList.length ? (
        <>
          <div className={styles.operate}>
            <div className={styles.setSource}>
              {dateList.length ? (
                <Select
                  className={styles.select}
                  value={selectedSourceDate}
                  onChange={(value) => {
                    setSelectedSourceDate(value);
                  }}
                >
                  {dateList.map((item) => {
                    return (
                      <Option value={item} key={item}>
                        {item?.replaceAll('-', '')}预测
                      </Option>
                    );
                  })}
                </Select>
              ) : (
                <></>
              )}
              <Select
                mode="multiple"
                style={{ width: 170 }}
                className={styles.select}
                value={selectedSourceId}
                onChange={changeSourceId}
                maxTagCount={1}
                maxTagTextLength={3}
              >
                {stations.map((item) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  );
                })}
              </Select>
              <div className={styles.customForecastBtn} onClick={customForecastHandle}>
                {/* <img className={styles.icon} src={config} /> */}
                <TjIcon gre={configGre} dark={config} className={styles.icon} />
                <span>自主调整</span>
              </div>
            </div>
            {/* <Radio
          className={styles.setAll}
          onClick={() => {
            setChecked(!checked);
          }}
        >
          对全部交易单元生效
        </Radio> */}
          </div>
          <div id="echart" className={styles.echartsLine}>
            {''}
          </div>
        </>
      ) : (
        <TRDefault type={'emptysm'} message={'暂无数据'} />
      )}

      <CustomPriceForecast
        onRef={customPriceForecastRef}
        tradeSequenceId={tradeSeqId}
        date={
          /* tradeSeqList?.filter((item) => item.tradeSequenceId === tradeSeqId)?.[0]?.forecastDate ||
          '' */
          forecastPriceV
        }
        defaultStationIds={[stationId]}
        defaultPointType="96"
        initLimitData={priceLimitData.map((item) => ({
          max: item.maxPriceLimit,
          min: item.minPriceLimit,
        }))}
        initData={yAxisData}
        onChange={updateData}
        provinceId={provinceId}
        version={selectedSourceDate}
      />
    </Modal>
  );
}

export default connect(
  ({ dayRollingTradeStragety, global }) => ({
    menuCode: global.configure.menuCode,
    tradeSeqId: dayRollingTradeStragety.tradeSeqId,
    stationId: dayRollingTradeStragety.stationId,
    stations: dayRollingTradeStragety.stations,
    hourOrderList: dayRollingTradeStragety.hourOrderList,
    tradeSeqList: dayRollingTradeStragety.tradeSeqList,
    echartsHourOrder: dayRollingTradeStragety.echartsHourOrder,
    provinceId: dayRollingTradeStragety.provinceId,
    forecastDate: dayRollingTradeStragety.forecastDate,
    forecastPriceV: dayRollingTradeStragety.forecastPriceV,
  }),
  null,
  null,
  { forwardRef: true },
)(forwardRef(PriceForecastModal));
